package com.e3roid.examples;

import android.graphics.Color;
import android.graphics.Typeface;
import android.view.MotionEvent;
import android.widget.Toast;

import com.e3roid.E3Activity;
import com.e3roid.E3Engine;
import com.e3roid.E3Scene;
import com.e3roid.drawable.sprite.TextSprite;

public class LabelResizeExample extends E3Activity {

	private final static int WIDTH  = 480;
	private final static int HEIGHT = 320;
	
	private TextSprite label;
	private StringBuffer textBuffer = new StringBuffer();
	private static final String[] SAMPLE_TEXT = {
			"The", "quick", "brown", "fox",
			"jumps", "over", "the", "lazy", "dog", "."
		};
	private int textIndex = 0;

	@Override
	public E3Engine onLoadEngine() {
		E3Engine engine = new E3Engine(this, WIDTH, HEIGHT);
		engine.requestFullScreen();
		engine.requestLandscape();
		return engine;
	}

	@Override
	public E3Scene onLoadScene() {
		E3Scene scene = new E3Scene();
		scene.addEventListener(this);
		scene.setBackgroundColor(0.94f, 1.00f, 0.94f, 1);
		
		// Label width and height cannot be determined before loading Label object.
		// So if you want to move the label relative to the label size, use move() method
		// after creating Label instance.
		label.move((getWidth() - label.getWidth()) / 2, (getHeight() - label.getHeight()) / 2);
		
		scene.getTopLayer().add(label);
		Toast.makeText(this, "Touch scren to add some text.", Toast.LENGTH_LONG).show();
		return scene;
	}

	@Override
	public void onLoadResources() {
		// Create new Label instance with parameters
		// fontSize is 18, foreground color is blue, background color is gray.
		label = new TextSprite(textBuffer.toString(), 18, Color.BLUE, Color.GRAY, Typeface.DEFAULT, this);
	}
	
	@Override
	public boolean onSceneTouchEvent(E3Scene scene, MotionEvent motionEvent) {
		if (label != null) {
			if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
				if (textIndex < SAMPLE_TEXT.length) {
					textBuffer.append(SAMPLE_TEXT[textIndex]);
					textBuffer.append(" ");
					textIndex++;
					
					// Update text and reload buffers.
					label.setText(textBuffer.toString());
					// If the text length has been changed, reload(true) needs to be called to resize the label.
					// The Label's reload(true) method re-creates OpenGL buffers to resize the label.
					label.reload(true);
					
					label.move((getWidth() - label.getWidth()) / 2, (getHeight() - label.getHeight()) / 2);
				}
			}
		}
		return false;
	}
}